﻿using Dapper;
using SuperHouse.Net.IRepositories;
using SuperHouse.Net.Models;
using SuperHouse.Net.Models.Dtos.Customer;
using SuperHouse.Net.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperHouse.Net.Repositories 
{
    /// <summary>
    /// 客户信息仓储
    /// </summary>
    public class CustomerRepository : BaseRepository<Customer>, ICustomerRepository
    {
        public async Task<PageResultModel<Customer>> GetAllCustomerPage(CustomerPageDto customerPageDto)
        {
           StringBuilder sbsql = new StringBuilder();
           StringBuilder sbmsql=new StringBuilder();
           StringBuilder wheresql=new StringBuilder();
            //结果集
            sbsql.Append(" select * from shop_customers");
            sbmsql.Append(" select count(1) from shop_customers");
            wheresql.Append(" where 1=1");
            if(!string.IsNullOrEmpty(customerPageDto.CustomerName))
            {
                //根据客户名称查询
                wheresql.Append(" and customer_name like '%" + customerPageDto.CustomerName + "%'");
            }
            if (!string.IsNullOrEmpty(customerPageDto.Telephone))
            {
                //根据客户电话查询
                wheresql.Append(" and telephone like '%" + customerPageDto.Telephone + "%'");
            }
            if (customerPageDto.Classification !=0)
            {
                //根据客户电话查询
                wheresql.Append(" and classification = '" + customerPageDto.Classification + "'");
            }
            //根据客户电话查询
            wheresql.Append(" and status = '1'");
            //拼接输入条件
            sbsql.Append(wheresql);
            sbsql.Append($" limit {(customerPageDto.PageIndex-1)*customerPageDto.PageSize} ,{customerPageDto.PageSize}");
            //拼接总条数条件
            sbmsql.Append(wheresql);
            //拿到结果集
            var list = (await _db.QueryAsync<Customer>(sbsql.ToString())).ToList();

            //总条数
            var count = await _db.ExecuteScalarAsync<int>(sbmsql.ToString());
            //返回模型
            PageResultModel<Customer> result = new PageResultModel<Customer>();
            //赋值
            result.TotalCount = count;
            result.PagedData = list;

            return result;

        }
    }
}
